package com.heima.search.listener;

import com.heima.common.constants.message.Article2EsConstants;
import com.heima.common.util.JsonUtils;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.search.service.UserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static com.heima.common.constants.message.Article2EsConstants.ARTICLE_2_ES_TOPIC;

@Slf4j
@Component
public class Article2EsListener {

    @Autowired
    private UserSearchService userSearchService;

    @KafkaListener(topics = ARTICLE_2_ES_TOPIC)
    public void receiveMsg(ConsumerRecord<String,String> record){
        Optional<ConsumerRecord> optional = Optional.ofNullable(record);
        if(optional.isPresent()){
            String value = record.value();
            log.info("接收到文章审核通过创建索引消息，value={}",record.value());
            ArticleDto articleDto = JsonUtils.toBean(value, ArticleDto.class);
            List<ArticleDto> articleDtoList = Arrays.asList(articleDto);
//            创建索引
            userSearchService.createIndexBatch(articleDtoList);
        }
    }
}
